define(["app", "moment", 'sortablejs', "module/system/program/myFavourite/favouriteService"], function (app, moment, sortablejs) {
    return ["$scope", "$filter", "$rootScope", "config", "$mdDialog", "$stateParams", "MMWService", "$timeout", 'RouterExtendProvider', "favouriteService",
    function ($scope, $filter, $rootScope, config, $mdDialog, $stateParams, $MMWService, $timeout, $RouterExtendProvider, $favouriteService) {
        $scope.subMenu;
        $scope.selectModel = '';
        $scope.selectPage = '';
        $scope.subMenuTags = {};
        userCustomReportGet();
        // 20220614 modify by Alan for#112054 : 修正功能選擇顯示邏輯
        $scope.isOpenSearchDialog = false;
        if($rootScope.chooseModule==='modelR'){//讓報表回到首頁時仍有分類功能
            $scope.chosenModule = $rootScope.chooseModule;
        }
        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        $scope.favouriteInfo = {
            UserNo: '',
            FavouriteList: [],
            DefaultProgram : ''
        };

        //$scope.menuTags = [{title:'设备'}, {title:'生产'}, {title:'人员'}, {title:'物料'}];
        var home_menu = JSON.parse(localStorage.getItem(config.appName + '_home_menu')||'{}');
        $scope.init = function(){

            $scope.appLogo = 'APP_logo_'+config.setting.lang;
            $scope.config = config;
            $scope.$root.selectHome = true; // 20220321 modify by chenshibo for#108564：超时登出后，重新登录，会出现两个侧边栏
            $scope.sideTools = $RouterExtendProvider.sideTools;
            angular.element(document.getElementById('home_left_menu')).removeClass('hide-left-menu');
            try{
                $scope.$root.hideMenu();
            }catch(e){}

            if(config.login){
                componentHandler.upgradeAllRegistered();
                try{
                    navigator.splashscreen.hide();
                }catch(e){}
                config.cache.account = config.login.account;
                config.cache.password = config.login.password;
                // 20230519 modify by Alan for#136015 : session要儲存到config裡面，以便後續使用
                if(config.login.session) {
                    config.mdssessionno = config.login.session
                }
                userPermissionsInfoGet(function(data){
                    //config.cache.autoLogin = true;
                    if(!config.login.session) {
                        config.mdssessionno = data.login_session_id;
                    }
                    config.cache.name = data.employee_name;
                    config.cache.isOutsideReport = data.isOutsideReport||'N';
                    // 20190506 modify by Dustdusk for M#57176:登入時帶回後台目前全部的系統參數
					config.cache.sys_parameter = data.sys_parameter||{};
                    //config.cache.isOutsideReport = 'Y';
                    //config.server.SMES_name = data.web_platform;
                    //config.server.SMES_port = data.web_port;
                    localStorage.removeItem('SMES_login');
                    localStorage.removeItem('sJDS_login');

                    if(typeof($RouterExtendProvider.MailStart) == 'function')
                        $RouterExtendProvider.MailStart();

                    if(data.employee_level != '0'){
                        config.cache.permissions = data.user_permissions_info_get;
                        nextStep();
                    } else {
                        config.cache.permissions = undefined;
                        nextStep();
                    }
                });
            } else {
                if(typeof($RouterExtendProvider.MailStart) == 'function')
                    $RouterExtendProvider.MailStart(function(){
                        if(config.setting.OperatingArea!=config.cache.account)
                            $RouterExtendProvider.AddToGroup([config.setting.OperatingArea]);
                    });
                nextStep();
            }
        };

        $scope.setting = function(){
            //$RouterExtendProvider.triggerSetting();
            $scope.$root.changeProgram('setting', {parent : 'home'});
        };

        $scope.config_setting = function () {
            $rootScope.hideSideSubMenu();
            $RouterExtendProvider.triggerSetting();
        };

        $scope.logout = function(){
            $rootScope.showConfirm($filter('translate')('home.msg.is_logout'),function(dialog){
                $rootScope.hideSideSubMenu();
                dialog.hide();
                $RouterExtendProvider.logout();
            });
        };

        $scope.$root.subMenu;
        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        $scope.menuClick = function(menuItem){
            $rootScope.hideSideSubMenu();
            $rootScope.chooseModule=menuItem.name;
            $RouterExtendProvider.goToModule(menuItem, showSubMenu);
            $scope.chosenModule = menuItem.name;
            $rootScope.menuTitle = menuItem.title;
        };

        function showSubMenu(menuItem){
            $scope.selectModel = menuItem.name;
            $scope.subMenu = $filter('filter')(menuItem.childs, {isShow:true});
            $scope.subMenuTags = {};
            //$scope.itemBGColor = menuItem.color;//20200615 add by Oliver for 將menu.json裡的子項目所有的background-color統一到父層管理
            //$scope.floorMneus = [];
            //var floorCount = 3;
            //var max_floor = 0; //二階選單最大層數
            if($scope.subMenu && $scope.subMenu.length>0){
                $scope.subMenu.forEach(function(menu){
                    if(home_menu[$scope.selectModel]){
                        //20181031 modify by Dustdusk for 增加順序調整
                        if(home_menu[$scope.selectModel][menu.name]){
                            if(home_menu[$scope.selectModel][menu.name].order != undefined)
                                menu.order = home_menu[$scope.selectModel][menu.name].order;
                            if(home_menu[$scope.selectModel][menu.name].show != undefined){
                                menu.isTempHide = home_menu[$scope.selectModel][menu.name].show?'N':'Y';
                            }
                        }

                    }
                    if(menu.tag == undefined){
                        menu.tag = 'others'
                    }
                    if($scope.subMenuTags[menu.tag] == undefined){
                        $scope.subMenuTags[menu.tag] = {
                            title : menu.tag,
                            show:true,
                            childs:[]
                        }
                    }
                    $scope.subMenuTags[menu.tag].childs.push(menu);
                });
            }
        }

        //處理subMenu顯示作業
        function checkSubMenu(Menu) {
            Menu.forEach(e => {
            //特殊處理
            switch (e.name) {
                case 'modelB':
                    if (window.cordova) {
                        //條碼標籤列印作業
                        e.childs = e.childs.filter(x => x.name !== 'modelB12')
                    }
                    break;

                default:
                    break;
            }
            });
            
            return Menu;
        }

        $scope.subMenuClick = function(menuItem){
            $RouterExtendProvider.goToProgram(menuItem);
            
        };
        $scope.final = function(callback){
            angular.element(document.getElementById('home_left_menu')).addClass('hide-left-menu');
            $rootScope.selectHome = false;
            callback();
        }
        $scope.options = function(){
            $mdDialog.serviceDialog('PasswordService', {
                mode:'confirm',
                feedback:function(){
                    $scope.$root.hideMenu();
                    var temp_programList = [];
                    $filter('orderBy')($scope.subMenu, 'order').forEach(function(menu_item){
                        temp_programList.push(angular.merge({
                            display:menu_item.name+' - '+$filter('translate')(menu_item.title).replace('<br>', ''),
                            isSelect:menu_item.isTempHide!='Y'
                        }, menu_item));
                    });
                    $mdDialog.dialog('JSplugins/angular-material-lite/template/checkList.tmp.html', function(dialog){
                        return {
                            title : $filter('translate')('home.change_program_order'),
                            beforeShown:function(){
                                // dialog.itemList.forEach(function(item){
                                //     if(item.isShow===true)
                                //         item.isSelect=true;
                                // })
                                var checklist_position = '';
                                if(!window.cordova)
                                    checklist_position = '#column-selector-list .ps-scrollbar-content';
                                else
                                    checklist_position = '#column-selector-list';

                                sortablejs.create($(checklist_position)[0], {
                                    ghostClass: 'ghost',
                                    filter: '.undragable',
                                    //handle: '.mdl-check-list__icon',
                                    onEnd: function (evt) {
                                        var newIndex = evt.newIndex;
                                        var oldIndex = evt.oldIndex;
                                        var chooseItem = dialog.itemList.splice(oldIndex, 1)[0];
                                        dialog.itemList.splice(newIndex, 0, chooseItem);
                                        dialog.itemList.forEach(function(item, index){
                                            item.order = index;
                                            //sheet.cssRules[(item.index*2)].style.order = item.order;
                                        });
                                        $scope.$apply();
                                    }
                                });
                            },
                            order:'order',
                            label : 'display',
                            code : 'name',
                            back : function() {
                                dialog.hide();
                                home_menu[$scope.selectModel] = {};
                                temp_programList.forEach(function(item){
                                    home_menu[$scope.selectModel][item.name] = {
                                        order:item.order,
                                        show:item.isSelect
                                    };
                                });
                                localStorage.setItem(config.appName + '_home_menu', JSON.stringify(home_menu));
                                $scope.$root.subMenu.childs = temp_programList;
                                showSubMenu($scope.$root.subMenu);
                            },
                            itemList : temp_programList,
                            itemClick : function(item, event){
                                item.isSelect = !item.isSelect;
                            },
                            confirm:function(){
                                dialog.hide();
                            },
                            isConfirm:true,
                            isDrag:true
                        };
                    });
                }
            });
        };

        function checkPermissions(menu, permissions){
            //最外層
            menu.forEach(function(menuItem){
                //20221021 modify by wangzy for M#0120911: H5端管理看板，只有DS可以查看，群组权限中找不到对应的权限分配
                if (menuItem.name == 'C01') {
                    $RouterExtendProvider.loadReportModuleNew(menuItem, function (menuItem) {
                        //中層
                        if (menuItem.childs) {
                            var firstMenuItem;
                            menuItem.childs.forEach(function (childItem) {
                                if (childItem.childs) {
                                    var firstSubMenuItem;
                                    childItem.childs.forEach(function (subChildItem) {
                                        if (permissions.indexOf(subChildItem.name) != -1) {
                                            subChildItem.isShow = true && subChildItem.isShow;
                                            if (!firstSubMenuItem) {
                                                firstSubMenuItem = subChildItem;
                                            }
                                        } else {
                                            subChildItem.isShow = false;
                                        }
                                    });

                                    if (childItem.panel) {
                                        if (permissions.indexOf(childItem.default) != -1) {
                                            childItem.isShow = true && childItem.isShow;
                                        } else {
                                            childItem.isShow = false;
                                        }
                                    } else {
                                        if (firstSubMenuItem) {
                                            if (permissions.indexOf(childItem.default) == -1 && childItem.default)
                                                childItem.default = firstSubMenuItem.name;
                                            childItem.isShow = true && childItem.isShow;
                                        } else {
                                            childItem.isShow = false;
                                        }
                                    }

                                    if (!firstMenuItem && childItem.isShow) {
                                        firstMenuItem = childItem;
                                    }
                                } else {
                                    if (permissions.indexOf(childItem.name) != -1) {
                                        childItem.isShow = true && childItem.isShow;
                                        if (!firstMenuItem) {
                                            firstMenuItem = childItem;
                                        }
                                    } else {
                                        childItem.isShow = false;
                                    }
                                }
                            });
                            if (menuItem.panel) {
                                if (permissions.indexOf(menuItem.default) != -1) {
                                    menuItem.isShow = true && menuItem.isShow;
                                } else {
                                    menuItem.isShow = false;
                                }
                            } else {
                                if (firstMenuItem) {
                                    if (permissions.indexOf(menuItem.default) == -1 && menuItem.default)
                                        menuItem.default = firstMenuItem.name;
                                    menuItem.isShow = true && menuItem.isShow;
                                } else if (menuItem.name == 'C01') {
                                    if (permissions.indexOf(menuItem.name) == -1)
                                        menuItem.isShow = false;
                                } else {
                                    menuItem.isShow = false;
                                }
                            }
                        }
                    });
                }
                else if (menuItem.name == 'C20') {
                    $RouterExtendProvider.loadKanbanModuleNew(menuItem, function (menuItem) {
                        //中層
                        if (menuItem.childs) {
                            var firstMenuItem;
                            menuItem.childs.forEach(function (childItem) {
                                if (childItem.childs) {
                                    var firstSubMenuItem;
                                    childItem.childs.forEach(function (subChildItem) {
                                        if (permissions.indexOf(subChildItem.name) != -1) {
                                            subChildItem.isShow = true && subChildItem.isShow;
                                            if (!firstSubMenuItem) {
                                                firstSubMenuItem = subChildItem;
                                            }
                                        } else {
                                            subChildItem.isShow = false;
                                        }
                                    });

                                    if (childItem.panel) {
                                        if (permissions.indexOf(childItem.default) != -1) {
                                            childItem.isShow = true && childItem.isShow;
                                        } else {
                                            childItem.isShow = false;
                                        }
                                    } else {
                                        if (firstSubMenuItem) {
                                            if (permissions.indexOf(childItem.default) == -1 && childItem.default)
                                                childItem.default = firstSubMenuItem.name;
                                            childItem.isShow = true && childItem.isShow;
                                        } else {
                                            childItem.isShow = false;
                                        }
                                    }

                                    if (!firstMenuItem && childItem.isShow) {
                                        firstMenuItem = childItem;
                                    }
                                } else {
                                    if (permissions.indexOf(childItem.name) != -1) {
                                        childItem.isShow = true && childItem.isShow;
                                        if (!firstMenuItem) {
                                            firstMenuItem = childItem;
                                        }
                                    } else {
                                        childItem.isShow = false;
                                    }
                                }
                            });
                            if (menuItem.panel) {
                                if (permissions.indexOf(menuItem.default) != -1) {
                                    menuItem.isShow = true && menuItem.isShow;
                                } else {
                                    menuItem.isShow = false;
                                }
                            } else {
                                if (firstMenuItem) {
                                    if (permissions.indexOf(menuItem.default) == -1 && menuItem.default)
                                        menuItem.default = firstMenuItem.name;
                                    menuItem.isShow = true && menuItem.isShow;
                                } else if (menuItem.name == 'C01') {
                                    if (permissions.indexOf(menuItem.name) == -1)
                                        menuItem.isShow = false;
                                } else {
                                    menuItem.isShow = false;
                                }
                            }
                        }
                    });
                }
                else {
                    //中層
                    if (menuItem.childs) {
                        var firstMenuItem;
                        menuItem.childs.forEach(function (childItem) {
                            if (childItem.childs) {
                                var firstSubMenuItem;
                                childItem.childs.forEach(function (subChildItem) {
                                    if (permissions.indexOf(subChildItem.name) != -1) {
                                        subChildItem.isShow = true && subChildItem.isShow;
                                        if (!firstSubMenuItem) {
                                            firstSubMenuItem = subChildItem;
                                        }
                                    } else {
                                        subChildItem.isShow = false;
                                    }
                                });

                                if (childItem.panel) {
                                    if (permissions.indexOf(childItem.default) != -1) {
                                        childItem.isShow = true && childItem.isShow;
                                    } else {
                                        childItem.isShow = false;
                                    }
                                } else {
                                    if (firstSubMenuItem) {
                                        if (permissions.indexOf(childItem.default) == -1 && childItem.default)
                                            childItem.default = firstSubMenuItem.name;
                                        childItem.isShow = true && childItem.isShow;
                                    } else {
                                        childItem.isShow = false;
                                    }
                                }

                                if (!firstMenuItem && childItem.isShow) {
                                    firstMenuItem = childItem;
                                }
                            } else {
                                if (permissions.indexOf(childItem.name) != -1) {
                                    childItem.isShow = true && childItem.isShow;
                                    if (!firstMenuItem) {
                                        firstMenuItem = childItem;
                                    }
                                } else {
                                    childItem.isShow = false;
                                }
                            }
                        });
                        if (menuItem.panel) {
                            if (permissions.indexOf(menuItem.default) != -1) {
                                menuItem.isShow = true && menuItem.isShow;
                            } else {
                                menuItem.isShow = false;
                            }
                        } else {
                            if (firstMenuItem) {
                                if (permissions.indexOf(menuItem.default) == -1 && menuItem.default)
                                    menuItem.default = firstMenuItem.name;
                                menuItem.isShow = true && menuItem.isShow;
                            } else if (menuItem.name == 'C01') {
                                if (permissions.indexOf(menuItem.name) == -1)
                                    menuItem.isShow = false;
                            } else {
                                menuItem.isShow = false;
                            }
                        }
                    }
                }
            });
        }

        function userPermissionsInfoGet(callback){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_SYS.user_permissions_info_get_json',
                content : {},
                success : function(data){
                    callback(data);
                }
            });
        }
            // 20231013 modify by shiwl for#0144676: 客户我的最爱自定义报表无法显示内容，麻烦看一下
        
            var customMenuChilld = [];  // 自定义报表菜单拼接 
            function userCustomReportGet(callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_custom_report_info_get',
                    content : {},
                    success : function(data){
                        customMenuChilld = data;
                        customMenuChilld.report_info.forEach(function(item){
                            item['isShow']= true;
                            item['displayText']= item.report_description;
                            item['name']= item.report_id;
                            item['icon']= "W_Com_User_Edit_nor_32";
                            item['title']= item.report_description;
                            item['isReport']= true;
                            
                        });
                        $favouriteService.get(config.cache.account, (data) => {
                            $scope.favouriteInfo = data; // 菜单拼接片段
                            var fragmentMenu = [];
                            if(customMenuChilld.report_info && customMenuChilld.report_info.length>0){
                                customMenuChilld.report_info.forEach(item=>{
                                    $scope.favouriteInfo.FavouriteList.forEach(function(flag){
                                        if(item.report_id == flag){
                                            fragmentMenu.push(item);
                                        }
                                    });
                                });
        
                                $rootScope.menu.forEach(function(item){
                                    if(item.name=="modelC"){
                                        item['childs'] = fragmentMenu;
                                    }
            
                                });
        
                            }
                        });
                    }
                });
         }
        function nextStep(){
            if(config.login && config.login.program){
                $scope.$root.changeProgram(config.login.program, {sideMenu:false, data:{
                    is_report:true,
                    report_name:decodeURI(config.login.program_name),
                    outside_url:config.cache.sys_parameter.FRURL
                }});
            } else {
                config.login = undefined;
                $rootScope.loadFinish = true;
                $scope.userInfo = config.cache.account.toUpperCase() +' ( '+config.cache.name+' )';
                $scope.envInfo = $filter('translate')('Login.env.'+config.setting.environment);
                config.menu = checkSubMenu(config.menu);//處理特殊menu顯示
                $rootScope.modules = $rootScope.menu = angular.merge([], config.menu);
                if(config.cache.permissions){
                    checkPermissions($rootScope.menu, config.cache.permissions);
                }            	
                // 20230328 modify by Alan for M#0122582 - 公司名稱
                $rootScope.companyName = config.cache.sys_parameter.CompanyName || '';
                // 20220726 modify by Alan for#107965 : 配合規格進行調整
                $favouriteService.get(config.cache.account, (data) => {
                    $scope.favouriteInfo = data;

                    if($scope.$root.subMenu){
                        // 20231211 modify by Alan for#152659: 移動#135955的修改至此
                        let menuItem = $rootScope.menu.find(module => module.name === $scope.$root.subMenu.name);
                        // 20220727 modify by Alan for#107965 : 修正返回首頁的跳轉邏輯
                        if($scope.$root.subMenu.name === 'myFavourite') {
                            $scope.myFavourite();
                        } else {
                            $scope.menuClick(menuItem);
                        }
                    } else if($rootScope.menu.length > 0){
                        var _menu = $filter('filter')($rootScope.menu, {isShow:true});
                        if(_menu.length > 0){
                            // 跳轉預設作業
                            if ($scope.favouriteInfo.DefaultProgram != '') {
                                goToDefaultProgram();
                            } else {
                                $scope.myFavourite();
                            }
                        }
                    }
                });
            }
        }

        $scope.getLogo = function(){
            return {'background-image': 'url("image/PN_home_'+config.setting.lang + '.png")'};
        };

        $scope.checkSubMenuTag = function(){
            return Object.keys($scope.subMenuTags).length == 1;
        }

        $scope.clickToShowModule = function (moduleInfo) {
            if (moduleInfo.status == 'show') {
                moduleInfo.status = 'hide';
            }else if (moduleInfo.status == 'hide') {
                moduleInfo.status = 'show';
            }
        };

        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        function goToDefaultProgram() {
            var modules = $filter('filter')($rootScope.menu, {isShow:true});
            var targetModule, targetProgram;
            // 20230321 modify by Alan for#131078 : 修正語法
            modules.forEach((module) => {
                module.childs && module.childs.forEach((programs) => {
                    if (programs.name === $scope.favouriteInfo.DefaultProgram) {
                        targetModule = module;
                        targetProgram = programs;
                    }
                })
            })
            if(targetModule) {
                $rootScope.chooseModule = targetModule.name;
                $RouterExtendProvider.goToModule(targetModule, showSubMenu);
                $scope.chosenModule = targetModule.name;
                $rootScope.menuTitle = targetModule.title;
                $RouterExtendProvider.goToProgram(targetProgram);
            }
        }

        // 20220613 modify by Alan for#112054 : 修改我的最愛跳轉邏輯
        $scope.editFavourite = function() {
            $RouterExtendProvider.myFavourite('edit');
        }

        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        $scope.hasFavourite = function() {
            return $scope.favouriteInfo.FavouriteList.length > 0;
        }

        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        $scope.isFavourite = function(program) {
            return $scope.favouriteInfo.FavouriteList.includes(program.name) > 0 && program.isShow
        }
        
        // 20230310 modify by Alan for#129828 : 我的最愛報錯
        $scope.isModuleHaveFavourite = function(module) {
            return module.childs && module.childs.some(program => {
                return $scope.isFavourite(program);
            });
        }

        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        $scope.openOptionDialog = function(program, event){
            event.stopPropagation();
            $mdDialog.serviceDialog('optionDialogService', {
                item: program,
                favouriteInfo: $scope.favouriteInfo
            }, (dialog) => {
                $scope.favouriteInfo = dialog.favouriteInfo;
            });
        }

        $scope.executeProgram = function(program) {
            $RouterExtendProvider.goToProgram(program);
        }

        // 20220726 modify by Alan for#107965 : 配合規格進行調整
        // 20220727 modify by Alan for#107965 : 修正返回首頁的跳轉邏輯
        $scope.myFavourite = function () {
            $rootScope.hideSideSubMenu();
            $scope.selectModel = 'myFavourite';
            $scope.$root.subMenu = {
                name: 'myFavourite',
            }
        };

        // 20220614 modify by Alan for#112054 : 開窗前暫存上一次的項目，關窗後還原上一次的項目
        $scope.openSearchDialog = function () {
            $rootScope.hideSideSubMenu();
            $scope.isOpenSearchDialog = true;
            var lastModel = $scope.selectModel;
            $scope.selectModel = '';
            $mdDialog.serviceDialog('searchDialogService', {}, () => {
                $scope.isOpenSearchDialog = false;
                $scope.selectModel = lastModel;
            });
        };

    }];
});
